package com.cube.dp.base.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author poker.li
 * @date 2021/12/13 17:55
 * <p>
 * http请求工具类
 */
public class RequestUtils {

    @Nullable
    public static ServletRequestAttributes currentServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取当前请求
     */
    @Nullable
    public static HttpServletRequest currentRequest() {
        ServletRequestAttributes requestAttributes = currentServletRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return requestAttributes.getRequest();
    }

    @Nullable
    public static Cookie[] currentCookies() {
        HttpServletRequest request = currentRequest();
        if (request == null) {
            return null;
        }
        return request.getCookies();
    }

    /**
     * 获取请求中某个属性的值<br/>
     * 获取顺序：【parameter】 -> head -> cookie
     *
     * @param attributeName 属性名
     * @return 属性值
     */
    @Nullable
    public static String currentRequestAttribute(@NonNull String attributeName) {
        HttpServletRequest request = currentRequest();
        if (request == null) {
            return null;
        }
        String value = request.getParameter(attributeName);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        String attributeValue = request.getHeader(attributeName);
        if (StringUtils.isNotBlank(attributeValue)) {
            return attributeValue;
        }
        String cookieValue = CookieUtils.getValue(attributeName);
        if (StringUtils.isNotBlank(cookieValue)) {
            return cookieValue;
        }
        return null;
    }
}
